/**
 * Copyright 2012 ibiblio
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package org.ibiblio.terasaur.search

import org.joda.time.DateTime
import org.joda.time.DateTimeZone
import org.ibiblio.terasaur.item.Item
import org.ibiblio.terasaur.search.DateHelper
import org.apache.solr.common.SolrDocument
import org.apache.log4j.Logger

/**
 * Wrapper to facilitate rendering solr query results.  Takes a SolrDocument
 * object and generates derived information.  Note that the torrent count and
 * bytes values are for published or available torrents.  The _torrents list
 * contains all torrents, even if not all torrents are published.  This allows
 * displaying correct non-public information to item editors.
 *
 * @author john
 */
class SolrItem {
    static SOLR_DELIMITER = ','
    private static final log = Logger.getLogger(this)

    public SolrDocument document
    private List _torrents
    private int _torrentCount
    private Long _torrentBytes

    SolrItem(SolrDocument solrDoc) {
        document = solrDoc
        try {
            _parseTorrents(document)
        } catch (Exception e) {
            log.error("Error parsing torrent data from solr (" + e.class.name + "): " + e.message, e)
        }
    }

    public int getTorrentCount() {
        return _torrentCount
    }

    public Long getTorrentBytes() {
        return _torrentBytes
    }

    /**
     * Parse torrent list in SolrDocument.  Check published datetime for
     * each torrent.  Save torrent count and total bytes.
     *
     * @param solrDoc
     * @return
     */
    private _parseTorrents(SolrDocument solrDoc) {
        _torrents = []
        _torrentBytes = 0L

        if (!solrDoc || !solrDoc.torrents) {
            return
        }

        Map torrentData
        DateTime now = DateHelper.now()
        solrDoc.torrents.each {torrent->
            torrentData = _getTorrentDataMap(torrent)
            if (torrentData.published.isBefore(now)) {
                ++_torrentCount
                _torrentBytes += torrentData.bytes
            }
            _torrents.add(torrentData)
        }
    }

    private Map _getTorrentDataMap(String torrentStr) {
        StringTokenizer st = new StringTokenizer(torrentStr, SOLR_DELIMITER)
        String infoHash = st.nextToken()
        Long bytes = Long.parseLong(st.nextToken())
        String publishedStr = st.nextToken()

        Map m = [
            'infoHash': infoHash,
            'bytes': bytes,
            'published': DateHelper.stringToDateTime(publishedStr)
            ]
        return m
    }

}
